/**  
 * 
 */
package com.astrocsr.action.securitylist;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.astrocsr.action.BaseAction;
import com.astrocsr.business.AuditLogManager;
import com.astrocsr.business.SecurityListManager;
import com.astrocsr.common.Constants;
import com.astrocsr.common.helper.ContextHelper;
import com.astrocsr.domain.db.SearchResult;
import com.astrocsr.domain.model.GroupModuleModel;
import com.astrocsr.domain.web.GroupInfo;
import com.astrocsr.domain.web.ModuleInfo;
import com.astrocsr.domain.web.SecurityListingInfo;
import com.opensymphony.xwork2.ModelDriven;

@Controller("groupModuleAction")
@Scope("prototype")
public class GroupModuleAction extends BaseAction implements
		ModelDriven<GroupModuleModel>,ServletRequestAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private GroupModuleModel model = new GroupModuleModel(); 

	private @Autowired
	SecurityListManager securityManager;
	
	private @Autowired
	AuditLogManager auditLogManager; 

	public GroupModuleModel getModel() {
		return model;
	}
	
	static final Logger log = Logger.getLogger(GroupModuleAction.class);

	public String initModule() throws Exception {
		log.info("initGroupModule.start");
		try {

			List<ModuleInfo> parentModuleList = securityManager.listModuleParent();
			model.setParentModuleList(parentModuleList);

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("initGroupModule.end");
		return SUCCESS;
	}
	
	public String executeSearchModule() throws Exception {
		log.info("executeSearchModule.start");
		try {
			// get listAccessrole from bussiness layer
			List<ModuleInfo> moduleInfoList = securityManager.listModule();

			// set listAccessrole to jsp
			model.setModuleInfoList(moduleInfoList);

			auditLogManager.addAuditlog(
					Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
					Constants.LOG_ActCode_Module_SER, 	//1 
					Constants.LOG_ActName_Module_SER, 	//2
					ContextHelper.getLoginId(), 		//3
					ContextHelper.getCurrentRole(), 	//4
					"Search All Modules",				//5
					request.getRemoteAddr()				//6
					);

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeSearchModule.end");
		return SUCCESS;
	}
	
	public String executeAddModule() throws Exception {
		log.info("executeAddModule.start");
		try {
			// Get module from jsp screen
			String moduleCode = model.getModuleCode();
			String moduleName = model.getModuleName();
			
			if (StringUtils.isNotBlank(moduleCode) && StringUtils.isNotBlank(moduleName)) {
				//Check moduleCode 
				String mCode = securityManager.getModuleCode(moduleCode);
				 
				if(StringUtils.isBlank(mCode)){ 
					ModuleInfo moduleInfo = new ModuleInfo(moduleCode, moduleName,
												ContextHelper.getLoginId(), new Date(),
												model.getModuleUri(), model.getOrderBy(), model.getParent());
					securityManager.addModule(moduleInfo);
					model.setSuccessMessage(getText("module.add.success"));
					// insert to auditlog

				} else {
					addActionMessage("Module Code "+mCode+" already exits"); 
				}
				auditLogManager.addAuditlog(
						Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
						Constants.LOG_ActCode_Module_Add, 	//1 
						Constants.LOG_ActName_Module_Add, 	//2
						ContextHelper.getLoginId(), 		//3
						ContextHelper.getCurrentRole(), 	//4
						"Add Module; moduleCode: " + moduleCode +"; moduleName: " + moduleName, //5
						request.getRemoteAddr()				//6
						);
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeAddModule.end");
		return SUCCESS;
	}

	public String executeDeleteModule() throws Exception{
		log.info("executeDeleteModule.start");
		try {
			// Get module from jsp screen 
			if (!StringUtils.isBlank(model.getModuleCode())) {
				securityManager.deleteModule(model.getModuleCode());
				model.setSuccessMessage(getText("module.delete.success"));
				// insert to auditlog
				auditLogManager.addAuditlog(
						Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
						Constants.LOG_ActCode_Module_DEL, 	//1 
						Constants.LOG_ActName_Module_DEL, 	//2
						ContextHelper.getLoginId(), 		//3
						ContextHelper.getCurrentRole(), 	//4
						"Delete Module; moduleCode: " + model.getModuleCode(), //5
						request.getRemoteAddr()				//6
						);
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeDeleteModule.end");
		return SUCCESS;
	}

	/* start group */
	public String initGroup() throws Exception {
		log.info("initGroup.start");
		try {
			String currentGroupCode = ContextHelper.getCurrentRole();
			// check group
			boolean b = securityManager.checkLastGroup(currentGroupCode);
			if (b) {
				return Constants.DENIED;
			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("initGroup.end");
		return SUCCESS;
	}
	
	public String executeSearchGroup() throws Exception {
		log.info("executeSearchGroup.start");
		try {
			//PagingInfo pagingInfo = model.getPagingInfo();
			//if (pagingInfo == null) {
			//	pagingInfo = new PagingInfo();
			//}
			
			// get listAccessrole from bussiness layer
			String currentGroup = ContextHelper.getCurrentRole();
			if (StringUtils.isNotBlank(currentGroup)) {
				SearchResult<GroupInfo> groupInfoList = securityManager.listGroupByParentCode(currentGroup, model.getGroupInfo(), null);
				model.setGroupInfoList(groupInfoList);
				/*
				if (groupInfoList != null) {
					if (groupInfoList.getPagingInfo() != null) {
						model.setPagingInfo(groupInfoList.getPagingInfo());
					} else {
						pagingInfo = new PagingInfo();
						pagingInfo.setTotal(groupInfoList.size());
						model.setPagingInfo(pagingInfo);
					}
				}
				*/
				
				auditLogManager.addAuditlog(
						Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
						Constants.LOG_ActCode_Group_SER, 	//1 
						Constants.LOG_ActName_Group_SER, 	//2
						ContextHelper.getLoginId(), 		//3
						ContextHelper.getCurrentRole(), 	//4
						"Search Group; currentGroup: " + currentGroup, //5
						request.getRemoteAddr()				//6
						);
			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeSearchGroup.end");
		return SUCCESS;
	}
	
	/**
	 * this method is used for "Assign Account" module
	 */
	public String executeSearchGroupByCurrentGroup() throws Exception {
		log.info("executeSearchGroupByCurrentGroup.start");
		try {
			String currentGroupCode = ContextHelper.getCurrentRole();
			if (StringUtils.isNotBlank(currentGroupCode)) {
				System.out.println("currentGroupCode = " + currentGroupCode);
				List<GroupInfo> groupInfoList = securityManager.listGroupByParentCode(currentGroupCode, null, null, true);
				model.setGroupInfoList(groupInfoList);
			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeSearchGroupByCurrentGroup.end");
		return SUCCESS;
	}
	
	public String executeAddGroup() throws Exception {
		log.info("executeAddGroup.start");
		try {
			// Get group from jsp screen
			String groupCode  = model.getGroupCode();
			String groupName  = model.getGroupName();
			//String parentCode = model.getParentCode();
			String parentCode = ContextHelper.getCurrentRole();
			
			if (StringUtils.isNotBlank(groupCode) && StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(parentCode)) {
				//Check moduleCode 
				boolean isExisted = securityManager.checkExistingGroupCode(groupCode);
				 
				if(!isExisted){ 
					GroupInfo groupInfo = new GroupInfo(groupCode, groupName, parentCode,
												ContextHelper.getLoginId(), new Date());
					securityManager.addGroup(groupInfo);
					model.setSuccessMessage(getText("group.add.success"));
					// insert to auditlog
					auditLogManager.addAuditlog(
							Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
							Constants.LOG_ActCode_Group_Add, 	//1 
							Constants.LOG_ActName_Group_Add, 	//2
							ContextHelper.getLoginId(), 		//3
							ContextHelper.getCurrentRole(), 	//4
							"Search Group; groupCode: " + groupCode + "; groupName: " + groupName, //5
							request.getRemoteAddr()				//6
							);
				} else {
					model.setFailMessage("Group Code "+ groupCode+" already exits"); 
				}
			} else {
				model.setFailMessage(getText("group.add.fail")); 
			} 
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeAddGroup.end");
		return SUCCESS;
	}

	public String executeUpdateGroup() throws Exception {
		log.info("executeUpdateGroup.start");
		try {
			// Get group from jsp screen
			String groupCode  = model.getGroupCode();
			String groupName  = model.getGroupName();

			String parentCode = ContextHelper.getCurrentRole();
			
			if (StringUtils.isNotBlank(groupCode) && StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(parentCode)) {
				//Check moduleCode 
				boolean isExisted = securityManager.checkExistingGroupCode(groupCode);
				 
				if(isExisted){ 
					GroupInfo groupInfo = new GroupInfo(groupCode, groupName, parentCode,
												ContextHelper.getLoginId(), new Date());
					securityManager.updateGroup(groupInfo);
					model.setSuccessMessage(getText("group.update.success"));
					// insert to auditlog
					auditLogManager.addAuditlog(
							Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
							Constants.LOG_ActCode_Group_UPT, 	//1 
							Constants.LOG_ActName_Group_UPT, 	//2
							ContextHelper.getLoginId(), 		//3
							ContextHelper.getCurrentRole(), 	//4
							"Search Group; groupCode: " + groupCode + "; groupName: " + groupName, //5
							request.getRemoteAddr()				//6
							);
				} else {
					model.setFailMessage("Group Code "+ groupCode+" is not existed now"); 
				}
			} else {
				model.setFailMessage(getText("group.update.fail")); 
			} 
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeUpdateGroup.end");
		return SUCCESS;
	}

	public String executeDeleteGroup() throws Exception{
		log.info("executeDeleteGroup.start");
		try {
			// Get module from jsp screen 
			if (!StringUtils.isBlank(model.getGroupCode())) {
				securityManager.deleteGroup(model.getGroupCode());
				model.setSuccessMessage(getText("group.delete.success"));
				// insert to auditlog
				auditLogManager.addAuditlog(
						Constants.LOG_ACCT_TYPE_ACTIVITY,		//0
						Constants.LOG_ActCode_Group_DEL, 	//1 
						Constants.LOG_ActName_Group_DEL, 	//2
						ContextHelper.getLoginId(), 		//3
						ContextHelper.getCurrentRole(), 	//4
						"Search Group; groupCode: " + model.getGroupCode(), //5
						request.getRemoteAddr()				//6
						);
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("executeDeleteGroup.end");
		return SUCCESS;
	}

	/* end group   */
	
	public String listSecurityListing() throws Exception {
		log.info("listSecurityListing.start");
		try {

			// get security listing information
			List<SecurityListingInfo> securityListingInfoList = securityManager.listSecurityListing();

			model.setSecurityListingInfoList(securityListingInfoList);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
		log.info("listSecurityListing.end");
		return SUCCESS;
	}
}
